<template>
  <div id="miniContainerToEnemy" class="minimap" >
    <div class="text">我方侦查敌方</div>
  </div>
</template>



<script>
import * as Cesium from 'cesium'
import {getHeading,getPitch,saveToImage} from "@/components/utils/utils";

export default {
  name: "MiniContainerToEnemy",
  props: {
    messageData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    showMiniContainerToEnemyDiv: {
      type: Boolean,
      default: false
       },
  },
  watch: {
    messageData: {
      handler(newData) {
        // 数据变化时自动执行
        this.updateViewer(newData)
      },
      deep: true, // 关键：深度监听
      immediate: true
    },
    showMiniContainerToEnemyDiv: {
      handler(newData) {
        this.ifSaveImage = newData
      }
        // 数据变化时自动执行
      }
  },
  data() {
    return {
      viewer: null,
      //每5帧截一次图
      saveToImageRate : 5,
      enemyStaType : 1,
      ifSaveImage : false,
      //是否初始化，为了防止地平线驱动无法初始化
      initCompleted: false,
    }
  },
  mounted() {
    this.viewer = new Cesium.Viewer('miniContainerToEnemy', {
      selectionIndicator: false,
      infoBox: false,
      animation: false,  //时钟
      timeline: false, // 底部时间线
      fullscreenButton: false, // 全屏
      vrButton: false, // VR
      sceneModePicker: false, // 选择视角的模式（球体、平铺、斜视平铺）
      baseLayerPicker: false, // 图层选择器（地形影像服务）
      navigationHelpButton: false, // 导航帮助(手势，鼠标)
      geocoder: false, // 位置查找工具
      homeButton: false,// 视角返回初始位置
      shadows: false,//阴影  未生效？
      terrainShadows: false,//阴影  未生效？
      creditContainer: "credit",
      scene3DOnly: true,
      // skyBox: false,       // 完全关闭默认星空
      skyAtmosphere: false, // 关闭大气散射效果
      maximumRenderTimeChange: Infinity,
      // shouldAnimate: true,  // 必须启用！
      // clockViewModel: new Cesium.ClockViewModel(viewer.clock)
      contextOptions: {
        webgl: {
          alpha: true,
          depth: true,
          stencil: true,
          antialias: true,
          premultipliedAlpha: true,
          // 通过canvas.toDataURL()实现截图需要将该项设置为true
          preserveDrawingBuffer: true,
          failIfMajorPerformanceCaveat: true
        }
        // requestWebgl1: true,
      }
    })
    this.viewer._cesiumWidget._creditContainer.style.display = 'none' // * 隐藏版权信息
    window.miniToEnemyViewer = this.viewer

  },
  methods: {
    updateViewer(messageData){
      if (messageData === '' || messageData === 'ok' || messageData === 'error' || messageData == null || Object.keys(messageData).length ===0) {
        return;
      }

      // console.log("收到服务端消息：" + messageData)
      const timeString = messageData.timestamp + (messageData.timestamp.endsWith('Z') ? '' : 'Z');
      const usSatellite = messageData.situation.usSatellite;
      const enemySatellite = messageData.situation.enemySatellite;
      const missileParam = messageData.situation.missileParam;
      const usWarning = messageData.showText.usWarning;
      const sceneStatus = messageData.sceneStatus;
      this.enemyStaType = messageData.enemyStaType;

      const stageName = messageData.stageName;
      const taskType  = messageData.taskType;
      const time = Cesium.JulianDate.fromIso8601(timeString);



      if (!this.initCompleted) {
        // 初始化时钟（以当前点为中心前后扩展）
        this.viewer.clock.startTime = time.clone();
        this.viewer.clock.stopTime = Cesium.JulianDate.addHours(time, 2, new Cesium.JulianDate());
        this.viewer.clock.currentTime = time.clone();
        this.viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP;
        this.viewer.clock.multiplier = 1;
        this.addEntity()
        this.initCompleted = true;
        console.log("miniToEnemy初始时钟设置完成");

      } else {
        this.viewer.clock.currentTime = time.clone();
        // 动态扩展时间轴
        if (Cesium.JulianDate.compare(time, this.viewer.clock.stopTime) > 0) {
          // con
          this.viewer.clock.stopTime = Cesium.JulianDate.addHours(time, 1, new Cesium.JulianDate());
        }
      }

      const enemyweixingentity = this.viewer.entities.getById('enemyweixing');
      const usweixingentity = this.viewer.entities.getById('usweixing');
      let missileEntity = this.viewer.entities.getById('missileweixing');

      //我方卫星：位置、姿态
      usweixingentity.position._value = Cesium.Cartesian3.fromDegrees(usSatellite.longitude, usSatellite.latitude, usSatellite.altitude)
      let r2 = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(usSatellite.direction), Cesium.Math.toRadians(usSatellite.pitch), Cesium.Math.toRadians(usSatellite.roll))
      usweixingentity.orientation = Cesium.Transforms.headingPitchRollQuaternion(usweixingentity.position._value, r2)


      if ('DN' === taskType){
        //导弹：位置、姿态
        missileEntity.position._value = Cesium.Cartesian3.fromDegrees(missileParam.longitude, missileParam.latitude, missileParam.altitude)
        let r = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(missileParam.direction), Cesium.Math.toRadians(missileParam.pitch), Cesium.Math.toRadians(missileParam.roll))
        missileEntity.orientation = Cesium.Transforms.headingPitchRollQuaternion(missileEntity.position._value, r)
        enemyweixingentity.show = false
        missileEntity.show = true

      }else {
        //敌方卫星：位置、姿态
        enemyweixingentity.position._value = Cesium.Cartesian3.fromDegrees(enemySatellite.longitude, enemySatellite.latitude, enemySatellite.altitude)
        const roll = this.enemyStaType === 1 ? enemySatellite.roll : enemySatellite.roll + 180
        let r = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(enemySatellite.direction), Cesium.Math.toRadians(enemySatellite.pitch), Cesium.Math.toRadians(roll))
        enemyweixingentity.orientation = Cesium.Transforms.headingPitchRollQuaternion(enemyweixingentity.position._value, r)
        missileEntity.show = false
        enemyweixingentity.show = true
      }

      //设置相机视角
      const targetEntity = 'DN' === taskType ? missileParam : enemySatellite
      const zhuPos = Cesium.Cartesian3.fromDegrees(usSatellite.longitude, usSatellite.latitude, usSatellite.altitude)
      const congPos = Cesium.Cartesian3.fromDegrees(targetEntity.longitude, targetEntity.latitude, targetEntity.altitude)
      const heading = getHeading(zhuPos, congPos)
      const pitch = getPitch(zhuPos, congPos)

      this.viewer.camera.position = congPos
      this.viewer.camera.setView({
        destination: zhuPos,
        orientation: {
          heading: heading,
          pitch: pitch,
          // roll: Cesium.Math.toRadians(-90)
        }
      })

      // 截图
      if (this.ifSaveImage && usWarning !== undefined && Object.keys(usWarning).length > 0 && sceneStatus !== 2) {
      // if (this.ifSaveImage ) {
        this.saveToImageRate < 6 ? this.saveToImageRate++ : this.saveToImageRate = 0
        if (this.saveToImageRate === 5) {
          saveToImage()
        }
      }

    },
    // 添加实体
    addEntity() {
      this.viewer.entities.add({
        id: 'enemyweixing',
        position: Cesium.Cartesian3.fromDegrees(108, 34, 5000),
        model: {
          uri: this.enemyStaType === 1 ? '/model/weixin.gltf' :'/model/calipso/scene.gltf',
          scale: this.enemyStaType === 1 ? 80 : 30,
          minimumPixelSize: this.enemyStaType === 1 ? 100 : 80,
          silhouetteSize: 1,
          silhouetteColor: Cesium.Color.WHITE
          // runAnimations: true,//启动模型自带的动画
        },
        label: {
          text: '敌方卫星',
          scale: 1,
          font: '10px sans-serif',
          fillColor: Cesium.Color.WHITE,
          pixelOffset: new Cesium.Cartesian2(20, -20)
        },
        // point: {
        //   color: new Cesium.Color(1, 0, 0, 0.5),
        //   pixelSize: 5
        // }
      })

      this.viewer.entities.add({
        id: 'usweixing',
        position: Cesium.Cartesian3.fromDegrees(108, 34, 5000),
      })


      this.viewer.entities.add({
        id: 'missileweixing',
        position: Cesium.Cartesian3.fromDegrees(108, 34, 5000),
        model: {
          show: true,
          uri: '/model/df.glb',
          scale: 20,
          minimumPixelSize: 50
        },
        label: {
          text: '导弹',
          scale: 1,
          font: '10px sans-serif',
          fillColor: Cesium.Color.WHITE,
          pixelOffset: new Cesium.Cartesian2(20, -20)
        },
        point: {
          color: new Cesium.Color(1, 0, 0, 1),
          pixelSize: 5
        }
      })


    }



  }
}
</script>

<style scoped>
.minimap {
  position: absolute;
  top: 8%;
  right: 600px;
  z-index: 100;
  height: 25%;
  width: 25%;
  border: #6adae8 3px solid;
}


.text {
  color: red;
  position: absolute;
  bottom: 0;
  right: 10px;
  z-index: 888;
}
</style>
